package ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

import base.BaseBean;
import base.activity.BaseFragmentActivity;
import bean.AppDataBean;
import bean.QiNiuUpTokeBean;
import bean.UnreadMsgBean;
import event.MainPageEvent;
import student.andlei.com.student.R;
import ui.fragment.HomePageFragment;
import ui.fragment.IntersionFragment;
import ui.fragment.MallFragment;
import ui.fragment.MineFragment;
import utils.GsonUtils;
import utils.SPUtils;
import utils.StringUtils;
import utils.log.LogUtil;
import view.BaseDialog;
import widget.MyRecyclerView.OnLoadListener;

public class MainActivity extends BaseFragmentActivity implements OnLoadListener {

    private RadioGroup rpTab;
    public static RadioButton rb_homepage, rb_inter, rb_mall, rb_mine;
    private static Fragment mineFragment;
    private Fragment homePageFragment;
    private Fragment interlocutionFragment;
    private Fragment mallFragment;
    private DownloadBuilder builder;
    public static TextView img_red_point;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mineFragment = MineFragment.getInstance();
        homePageFragment = HomePageFragment.getInstance();
        interlocutionFragment = IntersionFragment.getInstance();
        //historyorderFragment = HistoryOrderFragment.getInstance();
        mallFragment = MallFragment.getInstance();


        //addFragment(R.id.FrameLayout,historyorderFragment);
        addFragment(R.id.FrameLayout, homePageFragment);
        addFragment(R.id.FrameLayout, interlocutionFragment);
        addFragment(R.id.FrameLayout, mallFragment);
        addFragment(R.id.FrameLayout, mineFragment);
        hideAllFragment();
        showFragment(homePageFragment);
    }


    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.code == 200) {
            if (action.equals("common/versionInfo")) {
                final AppDataBean bean = (AppDataBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), AppDataBean.class);
                if (getVersion() != null) {
                    if (StringUtils.str2Int(bean.student.version) > getVersion()) {
                            initDownload(bean);
                    }
                }
            } else if (action.equals("common/qiniuUptoken")) {
                QiNiuUpTokeBean bean = (QiNiuUpTokeBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), QiNiuUpTokeBean.class);
                SPUtils.getInstance(this).put("uptoken", bean.uptoken);
                SPUtils.getInstance(this).put("domain", bean.domain);
                LogUtil.app("获取七牛token成功");
            }else if(action.equals("Qa/getNewsNumber")){
                UnreadMsgBean bean = (UnreadMsgBean) GsonUtils.getInstance(context).parseComplexJArrayByCommon(baseBean,UnreadMsgBean.class);
                if(bean.count>0){
                    MainActivity.img_red_point.setText(bean.count+"");
                    MainActivity.img_red_point.setVisibility(View.VISIBLE);
                }else {
                    MainActivity.img_red_point.setVisibility(View.GONE);
                }
            }
        } else {
            toast(baseBean.msg);
        }


    }

    @Override
    public void error(String action, Throwable e) {

    }
    private void initDownload(AppDataBean bean){
        builder = AllenVersionChecker
                .getInstance()
                .downloadOnly(UIData.create().setDownloadUrl(bean.student.url));
        builder.setCustomVersionDialogListener(new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData versionBundle) {
                BaseDialog baseDialog = new BaseDialog(context, R.style.dialog, R.layout.custom_dialog_one_layout);
                //versionBundle 就是UIData，之前开发者传入的，在这里可以拿出UI数据并展示
                TextView textView = baseDialog.findViewById(R.id.tv_msg);
                textView.setText("有新版啦，请更新新版本!");
                return baseDialog;
            }
        });
        builder.setShowDownloadingDialog(true); //默认true
        builder.setForceUpdateListener(new ForceUpdateListener() {
            @Override
            public void onShouldForceUpdate() {
                finishActivity();
            }
        });
        builder.setShowNotification(false); // 默认true
        builder.excuteMission(context);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void findViews() {
        post("Qa/getNewsNumber",BaseBean.class,false);
        img_red_point = getView(R.id.red_point);
        rpTab = (RadioGroup) findViewById(R.id.rd_group);
        rb_homepage = (RadioButton) findViewById(R.id.rd_menu_homepage);
        rb_inter = (RadioButton) findViewById(R.id.rd_menu_instion);
        rb_mall = (RadioButton) findViewById(R.id.rd_menu_mall);
        rb_mine = (RadioButton) findViewById(R.id.rd_menu_user);
        rb_homepage.setChecked(true);
    }

    @Override
    @SuppressWarnings("unchecked")
    protected void formatViews() {
        rpTab.setOnCheckedChangeListener(mOnCheckedChangeListener);
    }

    RadioGroup.OnCheckedChangeListener mOnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int i) {
            hideAllFragment();
            switch (i) {
                case R.id.rd_menu_homepage:
                    if (homePageFragment == null) {
                        homePageFragment = HomePageFragment.getInstance();
                    }
                    showFragment(homePageFragment);
                    break;
                case R.id.rd_menu_instion:
                    if (interlocutionFragment == null) {
                        interlocutionFragment = IntersionFragment.getInstance();
                    }
                    showFragment(interlocutionFragment);
                    break;
                case R.id.rd_menu_mall:
                    if (mallFragment == null) {
                        mallFragment = MallFragment.getInstance();
                    }
                    showFragment(mallFragment);
                    break;
                case R.id.rd_menu_user:
                    if (mineFragment == null) {
                        mineFragment = MineFragment.getInstance();
                    }
                    showFragment(mineFragment);
                    break;
            }
        }
    };

    public static void jumpToMineMyPoint() {
        rb_mine.setChecked(true);
        if (mineFragment == null) {
            mineFragment = MineFragment.getInstance();
        }
        ((MineFragment) mineFragment).GojumpMyPointFragment();
        //getChildFragmentManager().
        //mineFragment.GojumpMyPointFragment();
    }
    public static void jumpToMineMyClassTime() {
        rb_mine.setChecked(true);
        if (mineFragment == null) {
            mineFragment = MineFragment.getInstance();
        }
        ((MineFragment) mineFragment).GojumpMyClassTimeFragment();
        //getChildFragmentManager().
        //mineFragment.GojumpMyPointFragment();
    }
    //隐藏所有Fragment
    public void hideAllFragment() {
        hideFragment(mineFragment);
        hideFragment(homePageFragment);
        hideFragment(interlocutionFragment);
        hideFragment(mallFragment);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainPageEvent event) {
        if (event.firstPage == MainPageEvent.MINE_PAGE) {
            rb_mine.setChecked(true);
            rb_homepage.setChecked(false);
            rb_inter.setChecked(false);
            rb_mall.setChecked(false);
            mOnCheckedChangeListener.onCheckedChanged(rpTab, R.id.rd_menu_user);
        } else if (event.firstPage == MainPageEvent.MALL_PAGE) {
            rb_mine.setChecked(false);
            rb_homepage.setChecked(false);
            rb_inter.setChecked(false);
            rb_mall.setChecked(true);
            mOnCheckedChangeListener.onCheckedChanged(rpTab, R.id.rd_menu_mall);
        } else if (event.firstPage == MainPageEvent.HOME_PAGE) {
            rb_mine.setChecked(false);
            rb_homepage.setChecked(true);
            rb_inter.setChecked(false);
            rb_mall.setChecked(false);
            mOnCheckedChangeListener.onCheckedChanged(rpTab, R.id.rd_menu_homepage);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void formatData() {
        post("common/qiniuUptoken", BaseBean.class, false);
    }

    @Override
    protected void getBundle(Bundle bundle) {

    }

    private long clickTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == MotionEvent.BUTTON_BACK) {
            moveTaskToBack(false);
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (SystemClock.uptimeMillis() - clickTime <= 1500) {
                //如果两次的时间差＜1s，就不执行操作
                RichText.recycle();
                finishActivity();
            } else {
                //当前系统时间的毫秒值
                clickTime = SystemClock.uptimeMillis();
                toast("再点一次返回键退出应用");
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void loadData() {
        AppDataBean baseBean = new AppDataBean();
        final Map<String, String> map = new HashMap<>();
        map.put("citycode", String.valueOf(SPUtils.getInstance(this).getInt("CityCode")));
        // post("GetSystemTime",SPUtils.toJson(true, map),BaseBean.class,false);
//        start += count;
//        params = new HashMap<>();
//        params.put("start", start + "");
//        params.put("count", count + "");
//        post("top250", DouBanBean.class, false);
//        addressName.setText("上拉加载中");
    }

    @Override
    public boolean canLoadMore() {
        return true;
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        post("common/versionInfo", BaseBean.class, false);
//        AllenVersionChecker
//                .getInstance()
//                .requestVersion()
//                .setRequestMethod(HttpRequestMethod.POSTJSON)
//                .setRequestParams(httpParam)
//                //"http://qixi.banyuekj.com/teacher_api/common/versionInfo"
//                .setRequestUrl("http://qixi.banyuekj.com/teacher_api/common/versionInfo")
//                .request(new RequestVersionListener() {
//                    @Nullable
//                    @Override
//                    public UIData onRequestVersionSuccess(String result) {
//                        //拿到服务器返回的数据，解析，拿到downloadUrl和一些其他的UI数据
//                        Logger.i("result--->",""+result);
//                        //如果是最新版本直接return null
//                        return null;
//                                //UIData.create().setDownloadUrl(downloadUrl);
//                    }
//
//                    @Override
//                    public void onRequestVersionFailure(String message) {
//
//                    }
//                })
//                .excuteMission(context);
        // post("GetAppConfig", AppDataBean.class,false);
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */

    public Integer getVersion() {

        try {

            PackageManager manager = this.getPackageManager();

            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);

            String version = info.versionName;
            int VersionCode = info.versionCode;
            return VersionCode;

        } catch (Exception e) {

            e.printStackTrace();

            return null;

        }

    }
}
